// 源插件
import React, { PureComponent } from 'react';
import readXlsxFile from 'read-excel-file-forwps';
// 视图插件
import { Button, Icon, message } from 'antd';
// css OR less预编译器
import styles from './UploadExcel.less';

// 外部组件

// 图片

class UploadExcel extends PureComponent {
  componentWillMount() {}

  state = {
    filename: '',
    inputFlag: true,
  };

  changeInput() {
    const { name } = this.props;
    const input = document.getElementById(name);
    input.value = '';
  }

  render() {
    const { name } = this.props;
    const { filename, inputFlag } = this.state;

    return (
      <div>
        <Button className={styles['upload-wrap']} loading={!inputFlag} disabled={!inputFlag}>
          <Icon type="upload" />
          <input
            className={styles['file-uploader']}
            id={name}
            type="file"
            accept=".xlsx"
            onClick={this.changeInput.bind(this)}
          />
          <span className={styles['upload-text']}>{name}</span>
        </Button>
        <p className={styles['upload-tip']}>
          {filename === '' ? '只支持 .xlsx 格式的文件' : filename}
        </p>
      </div>
    );
  }

  componentDidMount() {
    const { name } = this.props;
    const { inputFlag } = this.state;
    const input = document.getElementById(name);

    input.addEventListener('change', upload.bind(this));
    function upload() {
      if (inputFlag) {
        const filename = input.files[0].name;
        if (filename.substr(filename.length - 5, 5) !== '.xlsx') {
          message.error('type Error');
          return;
        }
        this.setState({
          filename,
          inputFlag: false,
        });
        const { sheets, upload } = this.props;
        if (sheets.length === 0) {
          this.setState({
            inputFlag: true,
          });
          return;
        }
        const list = {};
        let j = 0;
        for (let i = 0; i < sheets.length; i++) {
          readXlsxFile(input.files[0], { sheet: sheets[i] }).then((rows, errors) => {
            if (typeof errors !== 'undefined') {
              message.error(errors);
              return;
            }
            list[sheets[i]] = rows;
            j++;
            if (j === sheets.length) {
              upload(list, filename);
              this.setState({
                inputFlag: true,
              });
            }
          });
        }
      }
    }
  }

  componentWillUnmount() {}
}

export default UploadExcel;
